package com.fingard.dsp.bank.directbank.crbc01.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class CrbankFileHash {


    /**
     * 获取文件的sha-1散列值
     * @param filename 文件名称，包含路径
     * @return  文件filename的散列值
     */
    public static String encrptySHA(String filename){
        return encrptySHA(filename, 0);
    }


    /**
     * 获取文件的sha-1散列值
     * @param filename  文件名称，包含路径
     * @param bufferSize 缓冲大小,默认为1M
     * @return 文件filename的散列值
     */
    public static String encrptySHA(String filename, int bufferSize) {
        // 文件读取流
        BufferedInputStream bis = null;
        // 散列计算实例
        MessageDigest md = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(filename));
            md = MessageDigest.getInstance("SHA-1");
            // 开始读取文件，一次读1M
            int size = 1024 * 1024;
            if(bufferSize>0){
                size=bufferSize;
            }
            byte[] temp = new byte[size];
            int len = 0;
            while ((len = bis.read(temp)) > 0) {
                md.update(temp, 0, len);
            }
            return byte2hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (FileNotFoundException e) {
            System.out.println("文件" + filename + "不存在");
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                    bis = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将字节转换为字符串
     * @param bs
     * @return
     */
    private static String byte2hex(byte[] bs){
        StringBuffer buffer=new StringBuffer();
        for(byte b:bs){
            String hex= Integer.toHexString(b&0xFF);
            hex=hex.length()==1?"0"+hex:hex;
            buffer.append(hex);
        }
        return buffer.toString();
    }
}
